import DataSetModel from "../model/DataSetModel";
import type { Query } from "mongoose";
import { BaseRes } from "../res-model";
import xlsx from "node-xlsx";
import fsx from "fs-extra";

export const setData = async (uuid: string, sheet: string, data: any) => {
  const find = await DataSetModel.findOne({ uuid, sheet });
  let res;
  if (find) {
    res = await DataSetModel.findOneAndUpdate(
      { uuid, sheet },
      {
        $push: { data },
      },
    );
  } else {
    res = await DataSetModel.create({
      uuid,
      sheet,
      data: [data],
    });
  }
  return new BaseRes({ code: 12345, message: "创建成功" });
};

export const getData = async (uuid: string) => {
  const res = await DataSetModel.find({ uuid });
  return res;
};

export const getDataByExcel = async (uuid: string) => {
  const data = await getData(uuid);
  const buffer = xlsx.build(
    data.map((item) => {
      return {
        name: item.sheet,
        data: item.data.reduce((prev, next, index) => {
          if (index === 0) {
            prev.push(Object.keys(next));
          }
          prev.push(Object.values(next));
          return prev;
        }, []),
        options: {},
      };
    }),
  );
  return buffer;
};

export const deleteData = async (uuid: string, sheet: string | null) => {
  const deleteOption = { uuid } as any;
  if (sheet) {
    deleteOption["sheet"] = sheet;
  }
  const res = await DataSetModel.deleteMany(deleteOption);
  return new BaseRes({ code: 12345, message: "删除成功" });
};
